package com.leyou.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.client.item.ItemClient;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.IdWorker;
import com.leyou.item.pojo.Sku;
import com.leyou.order.dto.CartDTO;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.dto.OrderVO;
import com.leyou.order.mapper.OrderDetailMapper;
import com.leyou.order.mapper.OrderLogisticsMapper;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.pojo.Order;
import com.leyou.order.pojo.OrderDetail;
import com.leyou.order.pojo.OrderLogistics;
import com.leyou.order.pojo.OrderStatusEnum;
import com.leyou.user.client.UserClient;
import com.leyou.user.pojo.AddressDTO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单业务
 */
@Service
@Transactional
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private UserClient userClient;
    @Autowired
    private AmqpTemplate amqpTemplate;


    @GlobalTransactional //使用分布式事务
    public Long buildOrder(OrderDTO orderDTO) {

        //1.获取当前登录信息
        UserInfo loginUser = UserHolder.getUser();

        //2.保存订单表信息
        Order order = new Order();
        order.setOrderId(idWorker.nextId());//订单编号（使用分布式ID）

        //获取购买的商品列表
        List<CartDTO> cartDTOS = orderDTO.getCarts();

        //取出所有商品的skuId集合
        List<Long> skuIdList = cartDTOS.stream().map(CartDTO::getSkuId).collect(Collectors.toList());

        //根据skuId集合查询Sku对象集合
        List<Sku> skuList = itemClient.findSkusBySkuIds(skuIdList);

        /**
         * Collectors.toMap()方法
         *    参数一： 声明转换为的Map集合的key的来源
         *    参数二： 声明转换为的Map集合的value的来源
         */
        Map<Long,Integer> cartsMap = cartDTOS.stream().collect(Collectors.toMap( CartDTO::getSkuId , CartDTO::getNum ));

      /*  Long totalFee = 0L;
        for(Sku sku:skuList) {
            totalFee += sku.getPrice() * cartsMap.get(sku.getId());
        };*/

        /**
         * map(): 对集合元素进行处理（获取属性、调用某个方法等），返回原来的类型
         * mapToLong()/MapToInt()/MapToDouble()：对集合元素进行处理（获取属性、调用某个方法等），以指定类型（long,int,double）返回
         *                                       这些方法还有对处理的结果进行再次统计（sum，avg等）
         */
        Long totalFee = skuList.stream().mapToLong( sku-> sku.getPrice()*cartsMap.get(sku.getId()) ).sum();


        //总金额= 所有商品的小计累加（每个商品小计=商品价格*购买的数量）
        order.setTotalFee(totalFee);//计算商品的总金额

        order.setActualFee(1L);//商品的实付金额，总金额-优惠价+邮费，为了支付方便，设置为1分钱

        order.setPromotionIds("1");//优惠活动

        order.setPaymentType(orderDTO.getPaymentType());//支付类型

        order.setPostFee(700L);//邮费

        order.setUserId(loginUser.getId());//下单人ID

        order.setInvoiceType(0);//发票类型

        order.setSourceType(2);//订单来源

        order.setStatus(OrderStatusEnum.INIT.value());//订单状态。目前为"未支付"

        orderMapper.insert(order);

        //3.保存订单明细表信息
        skuList.forEach(sku -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setId(idWorker.nextId());//明细ID
            orderDetail.setOrderId(order.getOrderId()); //订单编号

            //设置sku信息
            orderDetail.setSkuId(sku.getId());
            orderDetail.setNum(cartsMap.get(sku.getId()));
            orderDetail.setTitle(sku.getTitle());
            orderDetail.setPrice(sku.getPrice());
            orderDetail.setImage(sku.getImages());
            orderDetail.setOwnSpec(sku.getOwnSpec());

            orderDetailMapper.insert(orderDetail);
        });


        //4.保存订单物流表信息
        //查询当前用户指定的收货地址
        AddressDTO addressDTO = userClient.findAddressById(loginUser.getId(), orderDTO.getAddressId());

        OrderLogistics orderLogistics = BeanHelper.copyProperties(addressDTO,OrderLogistics.class);
        orderLogistics.setOrderId(order.getOrderId());
        orderLogistics.setLogisticsNumber("SF00001");
        orderLogistics.setLogisticsCompany("顺丰物流");

        orderLogisticsMapper.insert(orderLogistics);

        //5.扣减商品库存量
        itemClient.minusStock(cartsMap);

        //模拟异常
       // int i =100/0;

        //把skuId发送到MQ
        Map<String, Object> skuOrderMap = new HashMap<>();
        skuOrderMap.put("userId",loginUser.getId());
        skuOrderMap.put("skuIdList",skuIdList);
        amqpTemplate.convertAndSend(
                MQConstants.Exchange.ORDER_GENERATED_NAME,
                MQConstants.RoutingKey.ORDER_GENERATED_KEY,
                skuOrderMap);

        //返回订单编号
        return order.getOrderId();
    }
    //查询订单,订单id
    public OrderVO findOrderById(Long id) {

        //1.查询订单表
        Order order = orderMapper.selectById(id);

        //拷贝数据
        OrderVO orderVO = BeanHelper.copyProperties(order, OrderVO.class);

        //2.封装订单明细
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(id);
        QueryWrapper<OrderDetail> queryWrapper = Wrappers.query(orderDetail);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper);

        orderVO.setDetailList(orderDetails);

        //3.封装订单物流
        OrderLogistics orderLogistics = orderLogisticsMapper.selectById(id);
        orderVO.setLogistics(orderLogistics);

        return orderVO;
    }
}
